package com.example.myapplication1.study;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.res.AssetManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.myapplication1.R;
import com.faceunity.nama.ui.BeautyControlView;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.sql.BatchUpdateException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Copyright (C), 2020, 重庆八进制有限公司
 *
 * @author: weng
 * @last-modifier: weng
 * @version: 1.0
 * @create-date: 2021/1/6 16:10
 * @last-modify-date: 2021/1/6 16:10
 * @description:测试线程的 interrupted ，interrupted ，isInterrupted方法
 */
public class ThreadTestOfInteruptMethodActivity extends Activity {


    private Object object = new Object();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_threadtestofinteruptmethod);

        BottomSheetDialog beautyBottomSheetDialog = new BottomSheetDialog(this,R.style.dialog);
        Window window = beautyBottomSheetDialog.getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);
        beautyBottomSheetDialog.setContentView(R.layout.activity_bottomdialog);
        beautyBottomSheetDialog.show();
       final TextView test = findViewById(R.id.test);
//       test.setOnClickListener(new View.OnClickListener() {
//           @Override
//           public void onClick(View v) {
//               Toast.makeText(getBaseContext(),"1111",Toast.LENGTH_SHORT).show();
//               bottomwindow(test);
//           }
//       });

//        MyThead myThead = new MyThead();
//        myThead.start();
//        try {
//
//            Thread.sleep(20);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//
//        myThead.interrupt();

//        Thread t = new Thread(new TestJoin());
//        long start = System.currentTimeMillis();
//        t.start();

//        try {
//            t.join();//等待线程t 1000毫秒
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println(System.currentTimeMillis() - start);//打印出时间间隔
//        System.out.println("Main finished");//打印主线程结束

////        t1();
        String url = "https://www.12306.cn/index/";
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getDefault();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        builder.sslSocketFactory(sslContext.getSocketFactory(), new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                Log.e("tag",chain.length+"-----------");



            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                Log.e("tag",chain.length+"-----------");



            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {


                return new X509Certificate[0];
            }
        });
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {

                return true;
            }
        });
        OkHttpClient okHttpClient = builder.build();

        final Request request = new Request.Builder()
                .url(url)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
               e.printStackTrace();
               Log.e("tag", e.toString());

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.e("tag",response.body().string());



            }
        });

//        Executors.newSingleThreadExecutor().execute(new TestHttpsThread());

    }

   private PopupWindow popupWindow;
   public void bottomwindow(View view) {
        if (popupWindow != null && popupWindow.isShowing()) {
            return;
        }
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.activity_bottomdialog, null);
        popupWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //点击空白处时，隐藏掉pop窗口
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
//        popupWindow.setAnimationStyle(R.style.Popupwindow);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupWindow.showAsDropDown(view);

        //添加按键事件监听
        //添加pop窗口关闭事件，主要是实现关闭时改变背景的透明度
    }
    public class TestHttpsThread extends Thread{
        @Override
        public void run() {

            //自己写一个HttpUrlConnection发起网络请求
            String urlPath = new String("https://www.12306.cn/index/");

            //建立连接f
            URL url = null;
            try {
                url = new URL(urlPath);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            HttpURLConnection httpConn = null;
            try {
                httpConn = (HttpURLConnection) url.openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //设置连接超时,2000ms
            httpConn.setConnectTimeout(2000);
            //设置指定时间内服务器没有返回数据的超时，5000ms
            httpConn.setReadTimeout(5000);
            //设置参数
            httpConn.setDoOutput(true);   //需要输出
            httpConn.setDoInput(true);   //需要输入
            httpConn.setUseCaches(false);  //不允许缓存

            //设置请求属性,给请求头添加东西
            httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            httpConn.setRequestProperty("accept", "application/json");
            httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            httpConn.setRequestProperty("Charset", "UTF-8");
            //建立输入流，向指向的URL传入参数
            DataOutputStream dos = null;
            try {
                dos = new DataOutputStream(httpConn.getOutputStream());

            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                dos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获得响应状态
            //获得响应状态
            int resultCode = 0;
            try {
                resultCode = httpConn.getResponseCode();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (HttpURLConnection.HTTP_OK == resultCode) {
                StringBuffer sb = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = null;
                try {
                    responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    while ((readLine = responseReader.readLine()) != null) {
                        sb.append(readLine).append("\n");

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    responseReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i("zhangjiaren", sb.toString());
            }
        }

    }

    public class MyThead extends Thread {

        @Override
        public void run() {

            while (true) {
                synchronized (object) {

//                   System.out.println("interrupted------" + interrupted());
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println("中断");


                    } else {

                        System.out.println("1111111111111");

                    }
                    System.out.println("interrupted1------" + interrupted());


                }
            }
        }
    }

    private static void t1() {

        Thread t1 = new Thread() {

            @Override
            public void run() {
                synchronized (Thread.currentThread()) {

                    System.out.println("t1 running");
                    System.out.println("线程中断状态" + Thread.currentThread().isInterrupted());

                    try {
                        //等待，让线程被打标记为interrupted后再执行到wait方法
                        for (int i = 0; i < 10000; i++) {
                        }
                        Thread.currentThread().wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("线程中断状态" + Thread.currentThread().isInterrupted());


                }
            }
        };
        t1.start();
        t1.interrupt();

    }


    public class TestJoin implements Runnable {
        @Override
        public void run() {
            // synchronized (currentThread()) {
            for (int i = 1; i <= 5; i++) {
//            try {
//                Thread.sleep(1000);//睡眠5秒，循环是为了方便输出信息
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
                System.out.println("睡眠" + i);
            }
            System.out.println("TestJoin finished");//t线程结束


        }

    }


    public class MyAsyncTask extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] objects) {
            return null;
        }
    }

}
